#!/bin/bash

curPath=$(dirname $(readlink -f "$0"))
MONGO_HOME=${curPath}/mongodb
MONGO_PORT=61000
MONGO_BIND_IP=0.0.0.0
MONGO_BIN=${MONGO_HOME}/bin
MONGO_DATA=${MONGO_HOME}/data
MONGO_LOG=${MONGO_HOME}/logs/mongodb.log

MONGO_BIN_MONGOD=${MONGO_BIN}/mongod
MONGO_BIN_MONGO=${MONGO_BIN}/mongo

start()
{
    tmp=`ps -ef | grep "${MONGO_BIN_MONGOD} --bind_ip ${MONGO_BIND_IP} --port ${MONGO_PORT}" | wc -l`
    if [ $tmp -gt 1 ]; then 
      echo "The server arealdy started...abort!" 
      exit 1 
    fi 
    deleteLock
    cd ${MONGO_BIN}
    ${MONGO_BIN_MONGOD} --bind_ip ${MONGO_BIND_IP} --port ${MONGO_PORT} --dbpath ${MONGO_DATA} --fork --logpath ${MONGO_LOG} --logappend
    echo "${MONGO_BIND_IP} : ${MONGO_PORT}" 
    echo "Start MongoDB server in ${MONGO_BIN_MONGOD} OK!"    
}

stop()
{
    cd ${MONGO_BIN}
    ${MONGO_BIN_MONGO} --port ${MONGO_PORT} admin --eval "db.shutdownServer()"
    echo "Stopped MongoDB server"
}

usage()
{
        echo "Usage: $0 [start|stop|restart]"
}

deleteLock()
{
    echo "Deleting mongod.lock"
    cd ${MONGO_DATA}
    rm -f mongod.lock
    echo "Delete mongod.lock OK!"
}

if [ $# -lt 1 ];then
        usage
        exit
fi

if [ "$1" = "start" ];then
        start

elif [ "$1" = "stop" ];then
        stop

elif [ "$1" = "restart" ];then
        stop
        start

else
        usage
fi
